import { defineStore } from "pinia";
import { register,testlogin } from "@/api/api.ts";
import { resetRouter } from "@/router";
import { store } from "@/store";
import { useStorage } from "@vueuse/core";
export const useUserStore = defineStore("user", () => {
	// state
	const userIds = ref(); 
	const token = useStorage("accessToken", "");
	const phone = ref();
	const registerType = ref(0);
	const ishoveStatus = ref<boolean>(false);
	const tellcode = ref();
	const isSubInfo = ref<boolean>(false);
	const avatar = ref<string>('');
	const userCon = ref<any>();

	/**
	 * 登录调用
	 *
	 * @param {LoginData}
	 * @returns
	 */
	function login(loginData : any) {
		return new Promise<void>((resolve, reject) => {
			register(loginData)
				.then((response) => {
					console.log('res',response,response.code)
					const data = response.data;
					token.value = data.token; 
					phone.value = data.phone;
					userIds.value = data.id;
					userCon.value = data;
					if(response.code == 200){
						registerType.value = 0;
					}else{
						registerType.value = response.code;
						if(!response.data.identity){
							ishoveStatus.value = true;
						}else{
							ishoveStatus.value = false;
						}
						
					}
					resolve(response);
				})
				.catch((error) => {
					reject(error);
				});
		});
	}
	function testLog(loginData : any) {
		return new Promise<void>((resolve, reject) => {
			testlogin(loginData)
				.then((response) => {
					console.log('res',response,response.code)
					const data = response.data;
					token.value = data.token; 
					phone.value = data.phone;
					userIds.value = data.id;
					userCon.value = data;
					if(response.code == 200){
						registerType.value = 0;
					}else{
						registerType.value = response.code;
						if(!response.data.identity){
							ishoveStatus.value = true;
						}else{
							ishoveStatus.value = false;
						}
						
					}
					resolve(response);
				})
				.catch((error) => {
					reject(error);
				});
		});
	}
	return {
		token,
		phone,
		login,
		testLog,
		userIds,
		registerType,
		ishoveStatus,
		tellcode,
		isSubInfo,
		avatar,
		userCon
	};
},{
	persist: {
		key: 'dabaiuser', 
		storage: localStorage, 
		paths: ['phone','userIds','token','registerType','ishoveStatus','tellcode','isSubInfo','avatar','userCon'],
	},
});